﻿#region Using Directives

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.IO;

using QuickDev.Common.Audit;

using QuickDev.Localization;
using QuickDev.Web.UI;

using QuickDev.Model;
using QuickDev.BLL;
using QuickDev.Caching;
using QuickDev.Web.UI.Controls;
using System.Collections.Generic;
using QuickDev.Common.Utils;
using QuickDev.Common;

#endregion

namespace QuickDev.Web.App.Administration.Controls.Configuration
{
    public partial class providermanagement : AdminControl
    {
        #region Member Variables

        private ProviderType _providerType;

        #endregion

        #region Page Events

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load( object sender, EventArgs e )
        {
            try
            {
                SetProviderManagementProperties();
                SetProviderManagementLabel();

                if ( !Page.IsPostBack )
                {
                    LoadProviders();
                }
            }
            catch ( Exception ex )
            {
                Logger.Error( typeof( providermanagement ).Name + ".Page_Load", ex );
                base.MasterPage.MessageCenter.DisplayCriticalMessage( ex.Message );
            }
        }

        /// <summary>
        /// Handles the Click event of the lbEdit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void lbEdit_Click( object sender, CommandEventArgs e )
        {
            try
            {
                int providerId = -1;
                int.TryParse( e.CommandArgument.ToString(), out providerId );
                if ( providerId > 0 )
                {
                    LoadProvider( ProviderCache.GetModel( providerId ) );
                }
            }
            catch ( Exception ex )
            {
                Logger.Error( typeof( providermanagement ).Name + ".lbEdit_Click", ex );
                base.MasterPage.MessageCenter.DisplayCriticalMessage( ex.Message );
            }
        }

        /// <summary>
        /// Handles the Click event of the lbStatus control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void lbStatus_Click( object sender, CommandEventArgs e )
        {
            try
            {
                int providerId = -1;
                int.TryParse( e.CommandArgument.ToString(), out providerId );
                if ( providerId > 0 )
                {
                    Provider model = ProviderBLL.Update(providerId, (int)Utility.ChangeTypeTo(e.CommandName, typeof(Int32)) > 0 ? 0 : 1, Memberships.CurrentUserId);

                    if ( model == null )
                    {
                        MasterPage.MessageCenter.DisplayFailureMessage( string.Format( LocalizationUtility.GetText( "lblUnableToChangeStatus" ), typeof( Provider ).Name, model.Name ) );
                    }
                    else
                    {
                        LoadProviders();
                        MasterPage.MessageCenter.DisplaySuccessMessage( string.Format( LocalizationUtility.GetText( "lblStatusChanged" ), typeof( Provider ).Name ) );
                    }
                }
            }
            catch ( Exception ex )
            {
                Logger.Error( typeof( providermanagement ).Name + ".lbStatus_Click", ex );
                base.MasterPage.MessageCenter.DisplayCriticalMessage( ex.Message );
            }
        }

        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            if ( Page.IsValid )
            {
                try
                {
                    int providerId = 0;
                    int.TryParse( this.lblProviderId.Text, out providerId );
                    Provider model = null;
                    if ( providerId > 0 )
                    {
                        model = ProviderBLL.Update( providerId, (int)this.ProviderType, this.txtName.Text.Trim(), HttpUtility.HtmlEncode( this.txtDescription.Value ), this.txtConfigurationControlPath.Text.Trim(), Memberships.CurrentUserId );
                    }
                    else
                    {
                        model = ProviderBLL.Add( (int)this.ProviderType, this.txtName.Text.Trim(), HttpUtility.HtmlEncode( this.txtDescription.Value ), this.txtConfigurationControlPath.Text.Trim(), Memberships.CurrentUserId );
                    }

                    if ( model != null )
                    {
                        LoadProviders();
                        LoadProvider( model );
                        base.MasterPage.MessageCenter.DisplaySuccessMessage( LocalizationUtility.GetText( "lblProviderSaved" ) );
                    }

                    if ( model == null )
                    {
                        base.MasterPage.MessageCenter.DisplaySuccessMessage( string.Format( LocalizationUtility.GetText( "lblNotSaved" ), typeof( Provider ).Name ) );
                    }
                    else
                    {
                        LoadProviders();
                        LoadProvider( model );
                        base.MasterPage.MessageCenter.DisplaySuccessMessage( string.Format( LocalizationUtility.GetText( "lblSaved" ), typeof( Provider ).Name ) );
                    }
                }
                catch ( Exception ex )
                {
                    Logger.Error( typeof( providermanagement ).Name + ".btnSave_Click", ex );
                    base.MasterPage.MessageCenter.DisplayCriticalMessage( ex.Message );
                }
            }
        }

        /// <summary>
        /// Handles the Click event of the btnReset control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void btnReset_Click( object sender, EventArgs e )
        {
            Response.Redirect( HttpContext.Current.Request.Url.ToString() );
        }

        /// <summary>
        /// Handles the ItemDataBound event of the dgProviders control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.Web.UI.WebControls.DataGridItemEventArgs"/> instance containing the event data.</param>
        void dgProviders_ItemDataBound( object sender, DataGridItemEventArgs e )
        {
            if ( e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem )
            {
                LinkButton statusButton = e.Item.Cells[3].FindControl( "lbStatus" ) as LinkButton;
                if ( statusButton != null )
                {
                    statusButton.Text = (int)Utility.ChangeTypeTo(statusButton.CommandName, typeof(Int32)) > 0 ? LocalizationUtility.GetText("lbStatusActive") : LocalizationUtility.GetText("lbStatusInActive");
                }
            }
        }

        #endregion

        #region Methods

        #region Private

        /// <summary>
        /// Sets the provider list.
        /// </summary>
        private void LoadProviders()
        {
            List<Provider> providerCollection = ProviderCache.GetList( _providerType, CollectionsStatus.All );

            if ( providerCollection.Count > 0 )
            {
                pnlProviderList.Visible = true;
                dgProviders.DataSource = providerCollection;
                dgProviders.ItemDataBound += new DataGridItemEventHandler( dgProviders_ItemDataBound );
                dgProviders.Columns[0].HeaderText = LocalizationUtility.GetText( "hdrEdit" );
                dgProviders.Columns[1].HeaderText = LocalizationUtility.GetText( "hdrName" );
                dgProviders.Columns[2].HeaderText = LocalizationUtility.GetText( "hdrConfigurationControlPath" );
                dgProviders.Columns[3].HeaderText = LocalizationUtility.GetText( "hdrStatus" );
                dgProviders.DataBind();
            }
            else
            {
                pnlProviderList.Visible = false;
                base.MasterPage.MessageCenter.DisplayInformationMessage( SetNoProvidersLabel() );
            }
        }


        private void LoadProvider( Provider model )
        {
            lblProviderId.Text = model.ProviderId.ToString();
            txtName.Text = model.Name;
            txtDescription.Value = HttpUtility.HtmlDecode( model.Description );
            txtConfigurationControlPath.Text = model.ConfigurationControlPath;
        }

        /// <summary>
        /// Sets the no providers label.
        /// </summary>
        /// <returns></returns>
        private string SetNoProvidersLabel()
        {
            string message = string.Empty;
            switch ( this.ProviderType )
            {
                case ProviderType.ImmediateMessengerProvider:
                    message = LocalizationUtility.GetText( "lblNoImmediateMessengerProvidersInstalled" );
                    break;
                case ProviderType.DemographicsProvider:
                    message = LocalizationUtility.GetText( "lblNoDemographicsProvidersInstalled" );
                    break;
                case ProviderType.EmolumentProvider:
                    message = LocalizationUtility.GetText( "lblNoEmolumentProvidersInstalled" );
                    break;
                case ProviderType.AttendanceProvider:
                    message = LocalizationUtility.GetText( "lblNoAttendanceProvidersInstalled" );
                    break;
            }
            return message;
        }

        /// <summary>
        /// Sets the provider management properties.
        /// </summary>
        private void SetProviderManagementProperties()
        {
        }

        /// <summary>
        /// Sets the provider management label.
        /// </summary>
        private void SetProviderManagementLabel()
        {
            switch ( this.ProviderType )
            {
                case ProviderType.ImmediateMessengerProvider:
                    lblProviderManagement.Text = LocalizationUtility.GetText( "lblImmediateMessengerProviderManagement" );
                    break;
                case ProviderType.DemographicsProvider:
                    lblProviderManagement.Text = LocalizationUtility.GetText( "lblDemographicsProviderManagement" );
                    break;
                case ProviderType.EmolumentProvider:
                    lblProviderManagement.Text = LocalizationUtility.GetText( "lblEmolumentProviderManagement" );
                    break;
                case ProviderType.AttendanceProvider:
                    lblProviderManagement.Text = LocalizationUtility.GetText( "lblAttendanceProviderManagement" );
                    break;
            }
        }

        #endregion

        #endregion

        #region Properties


        /// <summary>
        /// Gets or sets the type of the provider.
        /// </summary>
        /// <value>The type of the provider.</value>
        public ProviderType ProviderType
        {
            get
            {
                return _providerType;
            }
            set
            {
                _providerType = value;
            }
        }

        #endregion
    }
}